package com.malou.server.reportes;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.malou.client.reportes.BalanceTienda;
import com.malou.client.reportes.EnviarCorreo;
import com.malou.client.reportes.ReporteService;
import com.malou.client.seguridad.usuario.Usuario;
import com.malou.server.base.Conexion;
import com.malou.server.base.util.Mail;
import com.malou.server.seguridad.usuario.Usuarios;

public class ReporteServiceImpl extends RemoteServiceServlet implements ReporteService {

	private static final long serialVersionUID = 1L;

	@Override
	public BalanceTienda getBalanceTienda(BalanceTienda blt) {
		
		if(blt.getTienda_id() == null){
			Usuario user = getUsuarioSession();		
			blt.setTienda_id(user.getIdtienda());
		}		
		return Reportes.getBalanceTienda(blt);	
	}
	
	private Usuario getUsuarioSession() {
		HttpSession session = getThreadLocalRequest().getSession(true);
		if (session.getAttribute("username") != null){
			String username = (String) session.getAttribute("username");
			
	        return Usuarios.getResponsable(username);  
	    }else{
	    	return null;
	    }
	}

	@Override
	public String getPdfReport(String fileName, HashMap<String, Object> param, Integer consulta_id) {
		String filePath = getServletConfig().getServletContext().getRealPath(fileName);		
		try {			
			JasperPrint print = getJasperPrint(fileName, param, consulta_id);
			
			String newFileName = filePath+".pdf";
			JasperExportManager.exportReportToPdfFile(print, newFileName);			
			
		} catch (SQLException e) {			
			e.printStackTrace();
		}catch (JRException e) {			
			e.printStackTrace();
		}
		
		return fileName+".pdf";
	}

	@Override
	public String getXlsReport(String fileName, HashMap<String, Object> param, Integer consulta_id) {
		String filePath = getServletConfig().getServletContext().getRealPath(fileName);		
		try {			
			JasperPrint print = getJasperPrint(fileName, param, consulta_id);			
			String newFileName = filePath+".xls";
			
			JRXlsExporter exporter = new JRXlsExporter();			
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);			
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, newFileName);			
			exporter.exportReport();
			
		} catch (SQLException e) {			
			e.printStackTrace();
		}catch (JRException e) {			
			e.printStackTrace();
		}
		
		return fileName+".xls";
	}
	
	private JasperPrint getJasperPrint(String fileName, HashMap<String, Object> param, Integer consulta_id) throws SQLException, JRException{
		
		String filePath = getServletConfig().getServletContext().getRealPath(fileName);
		Connection con;
		JasperPrint print=null;
		
		con = Conexion.getSqlMap().getDataSource().getConnection();
		if(param.get("tienda_id") == null){
			Usuario user = getUsuarioSession();		
			param.put("tienda_id", user.getIdtienda());
			param.put("tienda", user.getTienda());
		}
		
		preConsultas((Integer)param.get("tienda_id"), param, consulta_id);
		
		print = JasperFillManager.fillReport(filePath+".jasper", param, con);
		
		return print;		
	}

	@Override
	public Boolean sendMail(String fileName, HashMap<String, Object> param,	EnviarCorreo sn, Integer consulta_id) {
		String filePath = getServletConfig().getServletContext().getRealPath(fileName);
		Boolean rpta = true;
		try {			
			JasperPrint print = getJasperPrint(fileName, param, consulta_id);
			
			String newFileName = filePath+".pdf";
			JasperExportManager.exportReportToPdfFile(print, newFileName);
			
			if(!Mail.sendMessage(sn.getMensaje(), sn.getSubject(), sn.getDestino(),newFileName,fileName+".pdf")){				
				rpta = false;
			}
			
			
		} catch (SQLException e) {			
			e.printStackTrace();
		}catch (JRException e) {			
			e.printStackTrace();
		}
		return rpta;
	}	
	
	private void preConsultas(Integer tienda_id, HashMap<String, Object> param,Integer consulta_id){
		if(consulta_id != null)
		if(consulta_id == 1){
			Reportes.setActualStock(tienda_id, (Date)param.get("desde"), (Date)param.get("hasta"));
		}else if(consulta_id == 2){
			Reportes.setReporteSaldos(tienda_id, (Date)param.get("desde"), (Date)param.get("hasta"));
		}else if(consulta_id == 3){
			Reportes.setActualStock((Date)param.get("desde"), (Date)param.get("hasta"));
		}else if(consulta_id == 4){
			Reportes.setReporteSaldos((Date)param.get("desde"), (Date)param.get("hasta"));
		}
	}

	@Override
	public String createPdf(String fileName, HashMap<String, Object> param,
			Integer consulta_id, Integer id) {
		String filePath = getServletConfig().getServletContext().getRealPath(fileName);		
		try {			
			JasperPrint print = getJasperPrint(fileName, param, consulta_id);
			
			String newFileName = filePath+id+".pdf";
			JasperExportManager.exportReportToPdfFile(print, newFileName);			
			
		} catch (SQLException e) {			
			e.printStackTrace();
		}catch (JRException e) {			
			e.printStackTrace();
		}
		
		return fileName+id+".pdf";
	}
}
